package com.yueshop.cart.controller;

import com.yueshop.cart.interceptor.CartInterceptor;
import com.yueshop.cart.service.CartService;
import com.yueshop.cart.vo.Cart;
import com.yueshop.cart.vo.CartItem;
import com.yueshop.cart.vo.UserInfoTo;
import com.yueshop.common.constant.AuthConstant;
import com.yueshop.common.vo.MemberRespVo;
import jdk.nashorn.internal.objects.annotations.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
public class CartController {


    @Autowired
    CartService cartService;
    /**
     *  浏览器有一个cookie user-key 标识用户身份 1个月后过期
     *  第一次使用购物车功能 都会给一个临时身份
     *  浏览器以后保存了 每次访问都会带上这个cookie
     * @return
     */

    @GetMapping("getCheckedItem")
    @ResponseBody
    public List<CartItem> getCheckedItem(){
        return cartService.getCheckedItem();
    }



    //跳转购物车请求处理方法
    @GetMapping("/cart.html")
    public String cartListPage(Model model) throws ExecutionException, InterruptedException {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Cart cart =cartService.getCart();
        model.addAttribute("cart",cart);
        return "cartList";
    }


    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId")Long skuId, @RequestParam("num")Integer num) throws ExecutionException, InterruptedException {
        System.out.println("skuid:"+skuId+"num"+num);
        CartItem cartItem= cartService.addToCart(skuId,num);

        return "redirect:http://cart.yueshop.com/addToCartSuccess.html?skuId="+skuId;
    }


    @GetMapping("addToCartSuccess.html")
    public String addToCartSuccess(@RequestParam("skuId")Long skuId,Model model){
        CartItem cartItem =cartService.getCartItem(skuId);
        model.addAttribute("item",cartItem);
        return "success";
    }


    @GetMapping("/checkItem")
    public String checkItem(@RequestParam("skuId") Long skuId,@RequestParam("check")Integer check){
        cartService.checkItem(skuId,check);
        //修改完成之后重新查询
        return "redirect:http://cart.yueshop.com/cart.html";
    }

    @GetMapping("/countItem")
    public String countItem(@RequestParam("skuId") Long skuId,@RequestParam("num")Integer num){
        cartService.countItem(skuId,num);
        //修改完成之后重新查询
        return "redirect:http://cart.yueshop.com/cart.html";
    }


    //删除
    @GetMapping("/deleteItem")
    public String deleteItem(@RequestParam("skuId") Long skuId){
        cartService.deleteItem(skuId);
        //修改完成之后重新查询
        return "redirect:http://cart.yueshop.com/cart.html";
    }


}
